<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <input type="text" maxlength="13">
        <br>
        <span></span><br>
        <span class="res"></span>
    </div>
    <script>
        const oIpt = document.querySelector('input');
        const oSpan = document.querySelector('span');
        const res = document.querySelector('.res')
            //forward、backward、none，三种选择方向，默认为forward从前向后  that.setSelectionRange(0,that.value.length);
            // <input id="input01" type="text" value="测试文字测试文字" onfocus="getFocus(this)">
        function padStr(value, position, str, element) {
            position.forEach((v, i) => {
                if (value.length > v + i) {
                    value = value.substring(0, v + i) + str + value.substring(v + i)
                }
            })
            let len = value.length;
            requestAnimationFrame(() => {
                element.setSelectionRange(len, len)
            })
            return value
        }
        oIpt.oninput = function(e) {
            const event = e || window.event;
            let value = event.target.value;
            this.value = padStr(value.replace(/\D+/g, ''), [3, 7], ' ', event.target);
            oSpan.innerHTML = this.value;
            res.innerHTML = this.value.replace(/\D+/g, '')
        }
    </script>
</body>

</html>